package com.supermarket.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supermarket.entity.DTO.LoginLogDTO;
import com.supermarket.entity.LoginLog;
import com.supermarket.mapper.LoginLogMapper;
import com.supermarket.common.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;
    
    @Autowired
    private RedisUtil redisUtil;
    
    // Redis缓存相关的Key前缀
    private static final String LOGIN_LOG_LIST_KEY = "login:log:list";
    private static final String LOGIN_LOG_PAGE_KEY = "login:log:page";
    private static final int LOGIN_LOG_CACHE_SECONDS = 1800; // 登录日志缓存默认30分钟

    /**
     * 添加登录日志
     *
     * @param usrId 用户ID
     * @param loginIp 登录IP
     * @param status 登录状态
     * @return 影响的行数
     */
    public int addLoginLog(Integer usrId, Object loginIp, String status) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(usrId);
        loginLog.setLoginTime(new Date());
        if (StrUtil.isBlankIfStr(loginIp)){
            loginLog.setLoginIp("null");
        }else {
            loginLog.setLoginIp((String)loginIp);
        }
        loginLog.setStatus(status);
        int result = loginLogMapper.insert(loginLog);
        
        // 清除登录日志缓存
        if (result > 0) {
            clearLoginLogCache();
        }
        
        return result;
    }

    /**
     * 查询所有登录日志
     *
     * @return 登录日志列表
     */
    public List<LoginLogDTO> getAllLoginLogs() {
        String cacheKey = LOGIN_LOG_LIST_KEY;
        
        // 尝试从缓存获取
        Object cached = redisUtil.get(cacheKey);
        if (cached != null) {
            return (List<LoginLogDTO>) cached;
        }
        
        // 缓存未命中，查询数据库
        List<LoginLogDTO> loginLogs = loginLogMapper.selectAllLoginLogs();
        
        // 将结果存入缓存
        if (loginLogs != null && !loginLogs.isEmpty()) {
            redisUtil.set(cacheKey, loginLogs, LOGIN_LOG_CACHE_SECONDS);
        }
        
        return loginLogs;
    }

    /**
     * 根据ID删除登录日志
     *
     * @param id 登录日志ID
     * @return 影响的行数
     */
    public int deleteLoginLogById(Integer id) {
        int result = loginLogMapper.deleteById(id);
        
        // 清除登录日志缓存
        if (result > 0) {
            clearLoginLogCache();
        }
        
        return result;
    }

    /**
     * 分页查询登录日志
     *
     * @param pageNum  当前页码
     * @param pageSize 每页显示条数
     * @return 包含分页结果的 Map
     */
    public Map<String, Object> getAllLoginLogsByPage(int pageNum, int pageSize) {
        String cacheKey = LOGIN_LOG_PAGE_KEY + ":page" + pageNum + ":size" + pageSize;
        
        // 尝试从缓存获取
        Object cached = redisUtil.get(cacheKey);
        if (cached != null) {
            return (Map<String, Object>) cached;
        }
        
        // 缓存未命中，查询数据库
        // 使用 PageHelper 进行分页
        PageHelper.startPage(pageNum, pageSize);
        List<LoginLogDTO> loginLogs = loginLogMapper.selectAllLoginLogsByPage();

        // 获取分页信息
        PageInfo<LoginLogDTO> pageInfo = new PageInfo<>(loginLogs);

        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageInfo.getList());
        result.put("total", pageInfo.getTotal());
        result.put("pageNum", pageInfo.getPageNum());
        result.put("pageSize", pageInfo.getPageSize());
        result.put("pages", pageInfo.getPages());
        
        // 将结果存入缓存
        redisUtil.set(cacheKey, result, LOGIN_LOG_CACHE_SECONDS);

        return result;
    }
    
    /**
     * 清除登录日志缓存
     */
    private void clearLoginLogCache() {
        // 清除登录日志列表缓存
        redisUtil.delete(LOGIN_LOG_LIST_KEY);
        
        // 清除分页缓存
        Set<String> pageKeys = redisUtil.keys(LOGIN_LOG_PAGE_KEY + "*");
        if (pageKeys != null && !pageKeys.isEmpty()) {
            redisUtil.delete(pageKeys);
        }
    }
}